﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;

namespace BLL
{

    public class IPaddressConvert
    {
        /// <summary>
        /// 将区间内IP地址转换为List
        /// </summary>
        /// <param name="startIP"></param>
        /// <param name="endIP"></param>
        /// <returns></returns>
        public List<string> GenerateIPRange(string startIP, string endIP)
        {
            List<string> ipList = new List<string>();
            IPAddress start = IPAddress.Parse(startIP);
            IPAddress end = IPAddress.Parse(endIP);
            uint startUint = IPToUint(start);
            uint endUint = IPToUint(end);

            for (uint i = startUint; i <= endUint; i++)
            {
                ipList.Add(UintToIP(i).ToString());
            }

            return ipList;
        }

        private uint IPToUint(IPAddress ip)
        {
            byte[] ipBytes = ip.GetAddressBytes();
            Array.Reverse(ipBytes); // flip big-endian(network order) to little-endian
            return BitConverter.ToUInt32(ipBytes, 0);
        }

        private IPAddress UintToIP(uint ip)
        {
            byte[] ipBytes = BitConverter.GetBytes(ip);
            Array.Reverse(ipBytes); // flip little-endian back to big-endian(network order)
            return new IPAddress(ipBytes);
        }
    }

}